package cn.edu.scau.cmi.zhangjunming.hibernate.DAO;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.edu.scau.cmi.zhangjunming.hibernate.domain.Teacher;

public class TeacherDAO {

	private static final Logger log = LoggerFactory.getLogger(TeacherDAO.class);
	private Session session;
	private Transaction transaction;
	
	@SuppressWarnings("deprecation")
	private void setSession() {
		this.session = new Configuration().configure().buildSessionFactory().openSession();
	}

	public void save(Teacher teacher) {
		try {
			setSession();
			transaction=session.beginTransaction();
			session.save(teacher);
			transaction.commit();
			session.flush();
			session.close();
		}catch(RuntimeException re) {
			System.out.println(re.toString());
			throw(re);
		}
		
		
	}
	
	public void update(Teacher teacher) {
		try {
			setSession();
			transaction = session.beginTransaction();
			session.update(teacher);
			transaction.commit();
			session.flush();
			session.close();
		}catch(RuntimeException re) {
			System.out.println(re.toString());
			throw(re);
		}
		
		
	}
	
	public void delete(Teacher teacher) {
		try {
			setSession();
			transaction  = session.beginTransaction();
			session.delete(teacher);
			transaction.commit();
			session.flush();
			session.close();
		}catch(RuntimeException re) {
			System.out.println(re.toString());
			throw(re);
		}
	}
	
	public List<Teacher> listAll(){
		try {
			setSession();
			transaction  = session.beginTransaction();
			Query query = session.createQuery("from Teacher");
			@SuppressWarnings("unchecked")
			List<Teacher> list = (List<Teacher>)query.list();
			transaction.commit();
			session.flush();
			session.close();
			return list;
		}catch(RuntimeException re){
			//System.out.println(re.toString());
			//return null;
			throw(re);
		}
	}
	
	public boolean sameId(int n) {
		List<Teacher> list = listAll();
		for(int i=0;i<list.size();i++) {
			Teacher tea = list.get(i);
			if(tea.getId()==n) {
				return true;
			}
		}
		return false;
	}
}
